/* 
 *
 * Persistence4J - Simple library for data persistence using java
 * Copyright (c) 2010, Avdhesh yadav.
 * http://www.avdheshyadav.com
 * Contact: avdhesh.yadav@gmail.com
 *
 * This library is free software; you can redistribute it and/or modify it under the terms
 * of the GNU Lesser General Public License as published by the Free Software Foundation,
 * either version 3 of the License, or (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY;
 * without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
 * See the GNU Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public License along with this
 * library; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330,
 * Boston, MA 02111-1307, USA.
 *
 */
package com.avdy.p4j.common;

import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import org.apache.log4j.Logger;



/**
 * 
 * @author avdhesh
 *
 */
public class ReflectionUtil
{
	static Logger logger = Logger.getLogger(ReflectionUtil.class.getName());
	
	/**
	 * 
	 * @param object
	 */
	public static void describeInstance(Object object)
	{
	    Class<?> clazz = object.getClass();

	    Constructor<?>[] constructors = clazz.getDeclaredConstructors();
	    Field[] fields = clazz.getDeclaredFields();
	    Method[] methods = clazz.getDeclaredMethods();

	    logger.debug("Description for class: " + clazz.getName());
	    logger.debug("Summary");
	    logger.debug("-----------------------------------------");
	    logger.debug("Constructors: " + (constructors.length));
	    logger.debug("Fields: " + (fields.length));
	    logger.debug("Methods: " + (methods.length));


	    logger.debug("Details");
	    logger.debug("-----------------------------------------");

	    if (constructors.length > 0)
	    {
	      logger.debug("Constructors:");
	      for (Constructor<?> constructor : constructors) 
	      {
	    	  logger.debug(constructor);
	      }
	    }

	    if (fields.length > 0) 
	    {
	      System.out.println();
	      System.out.println("Fields:");
	      for (Field field : fields) 
	      {
	    	  logger.debug(field);
	      }
	    }

	    if (methods.length > 0)
	    {
	      System.out.println();
	      System.out.println("Methods:");
	      for (Method method : methods)
	      {
	    	  logger.debug(method);
	      }
	    }
	  }
	
	/**
	 * return new instance of class
	 * @param <T>
	 * @param clazz
	 * @return
	 * @throws IllegalArgumentException
	 * @throws SecurityException
	 * @throws InstantiationException
	 * @throws IllegalAccessException
	 * @throws InvocationTargetException
	 * @throws NoSuchMethodException
	 */
	public static <T> T newInstance(Class<T> clazz) throws IllegalArgumentException, SecurityException,InstantiationException, IllegalAccessException,InvocationTargetException, NoSuchMethodException 
	{
		return newInstance(clazz, new Class[0], new Object[0]);
	}

	
	/**
	 * returns new instance of class
	 * @param <T>
	 * @param clazz
	 * @param paramClazzes
	 * @param params
	 * @return
	 * @throws IllegalArgumentException
	 * @throws SecurityException
	 * @throws InstantiationException
	 * @throws IllegalAccessException
	 * @throws InvocationTargetException
	 * @throws NoSuchMethodException
	 */
	public static <T> T newInstance(Class<T> clazz, Class<?>[] paramClazzes,Object[] params) throws IllegalArgumentException, SecurityException, InstantiationException, IllegalAccessException,InvocationTargetException, NoSuchMethodException 
	{
		return clazz.getConstructor(paramClazzes).newInstance(params);
	}
	
	
	/**
	 * 
	 * @param className
	 * @return Object
	 * @throws ClassNotFoundException
	 * @throws IllegalAccessException
	 * @throws InstantiationException
	 */
	public static Object newInstance(String className) throws ClassNotFoundException, IllegalAccessException,InstantiationException
	{
		Object object = null;
		try 
		{
			object = (Object)Class.forName(className).newInstance();
		}
		catch (ClassNotFoundException e)
		{
			ClassLoader cl = Thread.currentThread().getContextClassLoader();
			object = (Object)cl.loadClass(className).newInstance();
		}
		return object;
	}
	
	
	/**
	 * 
	 * @param object
	 * @param fieldName
	 * @param newValue
	 * @throws NoSuchFieldException
	 * @throws IllegalArgumentException
	 * @throws IllegalAccessException
	 */
	public static void setFieldValue(Object object, String fieldName,Object newValue) throws NoSuchFieldException,IllegalArgumentException, IllegalAccessException
	{
		Class<?> clazz = object.getClass();
		Field field = getDeclaredField(object, fieldName);
		field.setAccessible(true);
		field.set(object, newValue);
	}
	
	/**
	 * 
	 * @param object
	 * @param name
	 * @return
	 * @throws NoSuchFieldException
	 */
	public static Field getDeclaredField(Object object, String name)throws NoSuchFieldException 
	{
		Field field = null;
		Class<?> clazz = object.getClass();
		do 
		{
			try 
			{
				field = clazz.getDeclaredField(name);
			} 
			catch (Exception e)
			{ }
		} while (field == null & (clazz = clazz.getSuperclass()) != null);

		if (field == null)
		{
			throw new NoSuchFieldException();
		}
		return field;
	}
	
	/**
	 * 
	 * @param object
	 * @param name
	 * @return
	 * @throws NoSuchMethodException
	 */
	public static Method getDeclaredMethod(Object object, String name)throws NoSuchMethodException 
	{
		Method method = null;
		Class<?> clazz = object.getClass();
		do 
		{
			try
			{
				method = clazz.getDeclaredMethod(name);
			}	
			catch (Exception e) 
			{ }
		}
		while (method == null & (clazz = clazz.getSuperclass()) != null);
		if (method == null) 
		{
			throw new NoSuchMethodException();
		}

		return method;
	}
	/**
	 * 
	 * @param object
	 * @param methodName
	 * @param arguments
	 * @return
	 * @throws NoSuchMethodException
	 * @throws IllegalArgumentException
	 * @throws IllegalAccessException
	 * @throws InvocationTargetException
	 */
	public static Object invokeMethod(Object object, String methodName,Object[] arguments) throws NoSuchMethodException,IllegalArgumentException, IllegalAccessException,InvocationTargetException 
	{
		  Method method = getDeclaredMethod(object, methodName);
		  method.setAccessible(true);
		  return method.invoke(object, arguments);
	}
	
	public static Object invokeMethod(Method method , Object obj, Object [] args) throws IllegalArgumentException, IllegalAccessException,InvocationTargetException  
	{
			Object object = method.invoke(obj, args);
			return object;
	}
	
	/**
	 * 
	 * @param clazz
	 * @return
	 */
	public static List <Field> getDeclaredFields(Class clazz) 
	{
		  List<Field> fields = new ArrayList<Field>();
		  do 
		  {
		    try
		    {
		      fields.addAll(Arrays.asList(clazz.getDeclaredFields()));
		    } 
		    catch (Exception e) { }
		  }
		  while ((clazz = clazz.getSuperclass()) != null);
		  return fields;
		}
	
	/**
	 * 
	 * @param object
	 * @param criteria
	 * @return
	 * @throws IllegalArgumentException
	 * @throws IllegalAccessException
	 */
	public static boolean search(Object object, String criteria)throws IllegalArgumentException, IllegalAccessException 
	{
		List <Field> fields = ReflectionUtil.getDeclaredFields(object.getClass());
		for (Field field : fields) 
		{
			field.setAccessible(true);
			if (String.valueOf(field.get(object)).equalsIgnoreCase(criteria)) 
			{
				return true;
			}
		}
		return false;
	}
	
	/**
	 * 
	 * @param object
	 * @return
	 */
	public static Method[] getMethods(Object object)
	{
		Method[] methods = object.getClass().getMethods();
		return methods;
	}
}
